/**
 * Created by yangfan on 2016/8/31.
 */
define(['config/appregister',"business/services/httpServices","business/services/commentService",
    "domReady","_","i18n","business/services/components","business/services/constant"],function(app,httpService,commentServices,domReady,_,i18n,components,constant){
    app.filter("bracket",function(){
        return function (input) {
            if(typeof input == "undefined" ||typeof input =="null")return;
            return "("+input + ")"
        }
    });
    app.directive('uiStar', function () {
        return {
            template: '<div class="rating " ng-mouseleave="leave()">' +
            '<p ng-repeat="star in stars track by $index" ng-class="star"  ng-click="click($index + 1)" ng-mouseover="over($index + 1)">' +
            '</p>' +
            '</div>',
            scope: {
                ratingValue: '=',
                max: '=',
                readonly: '@',
                onHover: '=',
                onLeave: '='
            },
            controller: function($scope){
                $scope.ratingValue = $scope.ratingValue || 0;
                $scope.max = $scope.max || 5;
                $scope.click = function(val){
                    if ($scope.readonly && $scope.readonly === 'true') {
                        return;
                    }
                    $scope.ratingValue = val;
                };
                $scope.over = function(val){
                    $scope.onHover(val);
                };
                $scope.leave = function(){
                    $scope.onLeave();
                }
            },
            link: function (scope, elem, attrs) {
                elem.css("text-align", "center");
                var updateStars = function () {
                    scope.stars = [];
                    for (var i = 0; i < scope.max; i++) {
                        scope.stars.push({
                            filled: i < scope.ratingValue
                        });
                    }
                };

                updateStars();

                scope.$watch('ratingValue', function (newValue, oldValue) {
                    if (newValue!=oldValue) {
                        updateStars();
                    }
                });
                scope.$watch('max', function (newValue, oldValue) {
                    if (newValue&&newValue!=oldValue) {
                        updateStars();
                    }
                });
                scope.getStar =function (index){

                }
            }
        };
    });
        app.directive("refreshValue",function(){
        return {
            require:"ngModel",
            link:function(scope,element,attrs,ctrl){
                scope.$watch("draw.size",function(newValue,oldValue){
                    if(newValue !=""){
                        ctrl.$setViewValue(scope.draw);
                    }
                })
            }
        }
    }).directive("uiComment",function($rootScope,$state){
        return {
            templateUrl:"app/business/services/comComponents/comComment.html",
            controller:function($scope,$element,$attrs,$q){
                $scope.textarea = "";
                //点击加载更多
                var pageNo = 1;
            },
            scope:{
                conf:"=commentConf"
            },
            link:function(scope,element,attrs){
                scope.i18n = i18n;
                scope.emoji = constant.QQface.emojis;
                scope.face = constant.QQface.face;
                scope.isShowCurSec = [];
                scope.isReplyTopComment = [];
                scope.isReplySecComment = [];
                scope.isReplySecTopComment = false;
                scope.isShowStar =false;
                scope.userInfo = $rootScope.userLoginInfo.data;
                //if(scope.conf.showStar && angular.isBoolean(scope.conf.showStar)){
                //    scope.isShowStar = scope.conf.showStar;
                //}
                if(!!scope.conf.showStar){
                    scope.isShowStar = true ;
                }else {
                    scope.isShowStar = false;
                }

                //配置评价标星 star
                if(scope.isShowStar){
                    scope.publishReadonly = false;
                    scope.publishRatingVal = 0;
                }
                /*点评管理*/
                scope.max = 5;//最大星级
                //scope.ratingVal = "";///默认星级，必需设置，下面同样名字覆盖，否则不显示；
                scope.readonly = true;//false可编辑，true不可编辑
                scope.topCommentReadOnly = true;
                scope.onHover = function(val){
                    scope.hoverVal = val;
                };
                scope.onLeave = function(){
                    scope.hoverVal = null;
                };

                var conf = scope.conf;
                var pageNo = 1;
                var screenWidth = window.screen.availWidth;
                var screenHeight =  window.screen.availHeight;
                scope.replies = "";

                //getTopComment
                function getTopComment(setpage){
                    if( typeof setpage == "number"){
                        pageNo = setpage;
                    }
                    var req = {
                        type:"GET",
                        base:conf.base,
                        url:conf.url,
                        uri:conf.uri.getTopComment,
                        data:{
                            id:conf.conf.id,
                            type:conf.conf.type,
                            pageSize:5,
                            all:false,
                            pageNo:pageNo
                        }
                    };

                    //通过setpage 来判断是否是点击更多
                    commentServices.updateCommentHttpServices(req).success(function(response){
                        if(!response.data){return};
                        scope.$apply(function(){
                            if(setpage && scope.list){
                                var arr =  scope.list.concat(response.data.list);
                                scope.list = arr;
                            }else{
                                scope.list = response.data.list;
                                scope.num = response.data.Pagination.totalCount;
                            }
                            scope.isShowTopPagination = pageNo >= Math.ceil(response.data.Pagination.totalCount/response.data.Pagination.pageSize)?false : true ;
                        });
                    })
                }

                //publish comment
                function publish(){
                    if(!$rootScope.userLoginInfo.logged){
                       $state.go('login');
                        return ;
                    }
                    var  req = {
                        type:"POST",
                        base:conf.base,
                        uri:conf.uri.publish,
                        url:conf.url,
                        data:{
                            id:conf.conf.id,
                            content:scope.textarea,
                            fkId:conf.conf.fkId,
                            type:conf.conf.type
                        }

                    };

                    if(scope.isShowStar){
                        req.data.evalCount = scope.publishRatingVal;
                    }
                    commentServices.updateCommentHttpServices(req).success(function(response){
                        scope.$apply(function(){
                            scope.textarea = "";
                            scope.publishRatingVal= 0;
                            alert(response.msg);

                        })
                    }).error(function(){
                        scope.$apply(function(){
                            scope.textarea = "";
                        })
                    })
                };
                function addReply(item){
                    var  req = {
                        type:"POST",
                        base:conf.base,
                        url:conf.url,
                        uri:conf.uri.reply,
                        data:{}
                    };

                    if(scope.isShowStar){
                        req.data ={
                            id:conf.conf.id,
                          //  fkId:conf.conf.fkId,
                            commentId:item.evaluateId,
                            content:scope.replies
                        }
                    }else {
                        req.data={
                            fkId:conf.conf.fkId,
                            commentId:item.commentId,
                            content:scope.replies
                        }
                    }
                    commentServices.updateCommentHttpServices(req).success(function(response){

                    });
                };
                //获取二级评论
                function getAllCommentsByTopId(item,setpage,isAll){
                    var pageNo = 1;
                    if( typeof setpage == "number"){
                        pageNo = setpage;
                    }
                    var req = {
                        type:"GET",
                        base:conf.base,
                        url:conf.url,
                        uri:conf.uri.getSecComment,
                        data:{
                            pageSize:2,
                            all:false,
                            pageNo:pageNo,
                            topId:item.commentId,
                            //id:item.id,
                            type:item.type
                        }
                    };
                    if(isAll == "all"){
                        req.data.all = true;
                    };
                    //通过setpage 来判断是否是点击更多
                    commentServices.updateCommentHttpServices(req).success(function(response){
                        if(!response.data){return};
                        scope.$apply(function(){
                            if(setpage ||isAll){
                                var arr =  scope.secComment.concat(response.data.list);
                                scope.secComment = arr;
                            }else{
                                scope.secComment = response.data.list;
                            }
                            scope.isShowSecPagination = pageNo >= Math.ceil(response.data.Pagination.totalCount/response.data.Pagination.pageSize)?false : true ;
                        });
                    });

                };
                getTopComment();

                //点击加载更多
                //var pageNo = 1;
                scope.loadMoreComment = function(){
                    pageNo++;
                    getTopComment(pageNo);
                };

                //发表评论
                scope.publish = function(){
                    scope.textarea = document.getElementById("f-publish").value;
                    publish();
                };

                //回复评论
                scope.addReply = function(item){
                    addReply(item);
                    scope.onchange.clearTextarea();
                };

                var secPage = 2;
                //得到二级评论
                scope.checkComment = function(item,index){
                    secPage = 2;
                    scope.currentItem1 = item;

                    var html = document.getElementById("comment-opacity-view");
                    $("#comment-opacity-view").addClass("comment-opacity-view").css("top",0).css("left",0)
                        .css("display","block")
                        .css("height",screenHeight)
                        .css("width",screenWidth);
                    var screenWidth2 = window.screen.availWidth;
                    scope.childCommentStyle = {
                        left:(screenWidth2-690)/2 +"px",
                        top:"20px"
                    };

                    //var divWidth = $(".f-childComment-window")[0].scrollWidth;
              //      var a =  $(".f-childComment-window").css("left",(screenWidth-divWidth)/2);
                   // $(".f-childComment-window").css()
                    scope.isShowCurSec = [];
                    scope.isShowCurSec[index] = true;
                    getAllCommentsByTopId(item);
                };
                //得到更多二级评论

                scope.checkMoreSecComment = function(item){
                    getAllCommentsByTopId(item,secPage);
                    secPage++;
                };
                scope.checkAllSecComment = function(item){
                    var isAll = "all";
                    getAllCommentsByTopId(item,secPage,isAll);
                };

                scope.closeSecComment = function(){
                    $("#comment-opacity-view").removeClass("comment-opacity-view")
                        .css("display","none");
                    scope.isShowCurSec = [];
                };
                scope.onchange = {
                    changeReplyTopComment:function(index){
                        if(typeof  scope.currentTopRepIndex == "number"&&scope.currentTopRepIndex == index){
                            scope.isReplyTopComment[index] = false;
                            scope.currentTopRepIndex =null;
                        }else{
                            scope.currentTopRepIndex = index;
                            scope.isReplyTopComment = [];
                            scope.isReplyTopComment[index] =true;
                        }
                    },
                    changeReplySecTopComment:function(){
                        scope.isReplySecTopComment = !scope.isReplySecTopComment;
                    },
                    changeReplySecComment:function(index){
                        if(typeof  scope.currentSecRepIndex == "number"&&scope.currentSecRepIndex == index){
                            scope.isReplySecComment[index] = !scope.isReplySecComment[index];
                        }else{
                            scope.currentSecRepIndex = index;
                            scope.isReplySecTopComment = false;
                            scope.isReplySecComment = [];
                            scope.isReplySecComment[index] =true;
                        }
                    },
                    clearTextarea:function(){
                        scope.replies = "";
                        scope.isReplyTopComment = [];
                        scope.isReplySecComment = [];
                        scope.isReplySecTopComment = false;
                    }
                };
                scope.isShowEmoji = false;
                var insertAtCaret = function(textDom,textFeildValue){
                    //   var textObj = $(this).get(0);
                    var textObj = textDom;
                    if(document.all && textObj.createTextRange && textObj.caretPos){
                        var caretPos=textObj.caretPos;
                        caretPos.text = caretPos.text.charAt(caretPos.text.length-1) == '' ?
                        textFeildValue+'' : textFeildValue;
                    } else if(textObj.setSelectionRange){
                        var rangeStart=textObj.selectionStart;
                        var rangeEnd=textObj.selectionEnd;
                        var tempStr1=textObj.value.substring(0,rangeStart);
                        var tempStr2=textObj.value.substring(rangeEnd);
                        textObj.value=tempStr1+textFeildValue+tempStr2;
                        textObj.focus();
                        var len=textFeildValue.length;
                        textObj.setSelectionRange(rangeStart+len,rangeStart+len);
                        textObj.blur();
                    }else{
                        textObj.value+=textFeildValue;
                    }
                }
                scope.emoji = {
                    onchange:function(){
                        scope.isShowEmoji  = !scope.isShowEmoji;
                    },
                    addEmoji :function(event,item,type){
                        if(type &&type == "publish"){
                            var textObj =   document.getElementById('f-publish');
                            insertAtCaret(textObj, item)

                            //  scope.textarea = scope.textarea + item;
                        }

                    }



                }
            }}
    }).directive("uiPraises",function(){
        return {
            scope:{
                item:"=getItem",
                conf:"=getConf"
            },
            require:"^uiComment",
            template:'<a  ng-bind="i18n.support" ng-click="support(item)"></a><a href="" ng-bind="praiseCount |bracket"></a>' +
            '<a ng-bind="i18n.oppose" ng-click="oppose(item)"></a> <a href="" ng-bind="stampCount |bracket"></a>',
            link:function(scope,element,attrs){
                var conf = scope.conf;
                scope.i18n = i18n;
                scope.praiseCount = 0;
                scope.stampCount = 0;
                scope.isShowStar =false;
                if(toString.call(scope.conf)=='[object Object]'){
                    if(scope.conf.hasOwnProperty("showStar") ){
                        scope.isShowStar = scope.conf.showStar;
                    }
                }
                if(scope.item){
                    scope.praiseCount = scope.item.praiseCount;
                    scope.stampCount = scope.item.stampCount;
                };
                function addPraise(item,type){
                    var commentId = item.commentId;
                    var  req = {
                        type:"POST",
                        base:conf.base,
                        uri:conf.uri.praise,
                        url:conf.url,
                        data:{}
                    };
                    //   非企业对外业务
                    if(scope.isShowStar){
                        req.data ={
                            //showStar 默认为评价
                            commentId:item.evaluateId,
                            praiseType:type
                        }
                    }else {
                        req.data={
                            commentId:item.commentId,
                            type:type
                        }
                    };
                    commentServices.updateCommentHttpServices(req).success(function(data){
                        scope.$apply(function(){
                            if(data.code&&data.code==110){
                                return;
                            }
                            if(type ==1){
                                scope.praiseCount+=1;
                            }
                            if(type ==2){
                                scope.stampCount+=1;
                            }
                        })
                    });
                }
                scope.support = function(item){
                    var  type =1;
                    addPraise(item,type);
                };
                scope.oppose = function(item){
                    var  type =2;
                    addPraise(item,type);
                };
            }
        }
    })

});
